<script setup>
import { ref, onMounted, watch } from 'vue';
import eventBus from 'vue3-eventbus';
import postApi from './api/modules/post';
import { initSettlementScreen, videInfo } from '@/utils/indexedDB'

import Player from './components/Player.vue';
import Leaderboard from './components/Leaderboard.vue';
import LoadingOverlay from './components/LoadingOverlay.vue';

import image_1 from './assets/1.png';
import image_2 from './assets/2.png';
import image_3 from './assets/3.png';
import image_4 from './assets/4.png';

// 玩家数据
const playerLevel = 0.5;
const arr = ref([
    {
        name: '暂无玩家',
        playerAvatar: image_2,
        score: 0,
        startPoint: { x: 20, y: 35 },
        endPoint: { x: 13, y: 20 }
    },
    {
        name: '暂无玩家',
        playerAvatar: image_1,
        playerScore: 0,
        startPoint: { x: 41.7, y: 31.7 },
        endPoint: { x: 45, y: 20 }
    },
    {
        name: '暂无玩家',
        playerAvatar: image_3,
        playerScore: 0,
        startPoint: { x: 54.2, y: 50 },
        endPoint: { x: 71, y: 35 }
    },
    {
        name: '暂无玩家',
        playerAvatar: image_4,
        playerScore: 0,
        startPoint: { x: 75, y: 50 },
        endPoint: { x: 84, y: 40 }
    }
]);
const videoSrc = ref("");
const duration = 2;
const stayDuration = 7.5;
const initialScale = 0.1;
const showVideo = ref(false);

// 视频和动画控制
const videoRef = ref(null);
const initialTime = 0.5; // 视频加载时显示第 0.5 秒的画面
const visible = ref(false); // 控制加载动画的显示
const tmp = ref(null);

let timer = null;

const startAll = () => {
    resetAll();
    setTimeout(() => {
        clearTimeout(timer);
        videoRef.value.play();
        eventBus.emit('start-animation');
        timer = setTimeout(() => {
            if (tmp.value != null) {
                showSettlement(tmp.value);
                tmp.value = null;
                return;
            }
            showVideo.value = false;
        }, 9000)
    }, 200)
};

const resetAll = () => {
    videoRef.value.pause();
    videoRef.value.currentTime = initialTime;
    eventBus.emit('reset-animation');  
};


const handleSocketMessage = async (message) => {
    console.log('接收到消息:', message);
    let { playerNames } = message;
    if (playerNames.length <= 0) return;

    let { data } = await postApi.getLeaderboard(message);
    let value = data.data;
    
    console.log('从服务器获取到的数据', value);
    if (value.length <= 0) return;
     
    [value[0], value[1]] = [value[1], value[0]]
    
    // 更新前4个玩家数据
    const frontPlayers = value.slice(0, 4);
    frontPlayers.forEach((player, index) => {
        arr.value[index].name = player.name;
        arr.value[index].score = player.score;
    });
    
    // 如果有更多玩家，添加到数组末尾
    if (value.length > 4) {
        arr.value.splice(4);
        const remainingPlayers = value.slice(4); // 从第5个元素开始，避免重复
        remainingPlayers.forEach(player => {
            arr.value.push(player);
        });
    }
}

const showSettlement = async (message) => {
    showVideo.value = true;
    let { team } = message;
    team == 0 ? videoSrc.value = videInfo.value[0].indexDB_URL : videoSrc.value = videInfo.value[1].indexDB_URL
    visible.value = true;
    try {
        await handleSocketMessage(message);
    } catch (error) {
        console.error('Error handling socket message:', error);
    } finally {
        setTimeout(() => {
            visible.value = false;
            startAll();
        }, 200)
    }
}

watch(()=> videInfo.value[0].isLoadSuccess && videInfo.value[1].isLoadSuccess, (newValue)=> {
    if (newValue == true) {
        videoRef.value.load();
        videoSrc.value = videInfo.value[0].indexDB_URL
        videoRef.value.onloadedmetadata = () => {
            console.log(`视频加载完成，设置初始画面为 ${initialTime} 秒`);
            if (initialTime >= 0 && initialTime <= videoRef.value.duration) {
                videoRef.value.currentTime = initialTime;

                // 监听视频时间更新事件
                videoRef.value.ontimeupdate = () => {
                    // 如果视频播放到倒数第1秒，就暂停播放
                    if (videoRef.value.currentTime >= videoRef.value.duration - 1) {
                        videoRef.value.pause();
                    }
                };
                // 视频加载完成才开始监听
                eventBus.on('socket-message', message => {
                    console.log('接收到消息:', message);
                    if (showVideo.value == true) {
                        tmp.value = message;
                    } else {
                        showSettlement(message);
                    }
                });
            } else {
                console.warn(`initialTime ${initialTime} 超出视频时长 ${videoRef.value.duration}，设置为 0`);
                videoRef.value.currentTime = 0;
            }
        };
    }
})

onMounted(() => {
    initSettlementScreen();
});
</script>

<template>
    <LoadingOverlay 
        :visible="!videInfo[0].isLoadSuccess || !videInfo[1].isLoadSuccess" 
        :text="videInfo[0].txt + '\n' + videInfo[1].txt + '\n' + 'PS: 只需下载一次，下载过程中退出网页将重新下载，结算画面最终将保存在浏览器中'"
    />
    <LoadingOverlay :visible="visible" />
    <div class="box" v-show="showVideo">
        <div class="video-container">
            <video ref="videoRef" 
                :src="videoSrc" 
                muted 
                class="fullscreen-video" 
                preload="auto" 
            />
            <Player
                v-for="item in arr.slice(0, 4)"
                :key="item.name"
                :player-name="item.name"
                :player-avatar="item.playerAvatar"
                :player-level="playerLevel"
                :player-score="item.score"
                :start-point="item.startPoint"
                :end-point="item.endPoint"
                :duration="duration"
                :stay-duration="stayDuration"
                :initial-scale="initialScale"
            />
            <Leaderboard v-if="arr.length > 4" :players="arr.slice(4, arr.length)"/>
        </div> 
    </div>
</template>

<style lang="less">
.box {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    .video-container {
        position: relative;
        width: 100%;
        height: 100%;
        overflow: hidden;
        z-index: 1;
        .fullscreen-video {
            height: 100%;
            width: 100%;
            display: block;

        }
    }

}
</style>